package com.zpy.SmartChargeStation.mqtt.client.factory;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zpy.SmartChargeStation.iotdb.service.IoTDBService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

/**
 * description: 接收消息的处理
 */

@Component
@Slf4j
public class InBoundMessageRev implements MessageHandler {

    @Resource
    private IoTDBService ioTDBService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        // 获取消息主题
        String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
        String payload = message.getPayload().toString();

        // 根据不同主题处理消息
        if ("charge/stat".equals(topic)) {
            // 处理来自ESP8266的电流监测数据
            log.info("收到ESP8266电流监测数据，主题: {}，内容: {}", topic, message.getPayload().toString());
            // 在这里可以添加处理电流监测数据的业务逻辑
            try {
                // 解析JSON格式的数据
                JSONObject jsonData = JSON.parseObject(payload);
                double current = jsonData.getDouble("current");
                // 如果JSON中包含时间戳则使用，否则使用当前系统时间
                long timestamp = jsonData.containsKey("timestamp") ?
                        jsonData.getLong("timestamp") : System.currentTimeMillis();

                // 存储电流数据到IoTDB
                ioTDBService.insertCurrentData(current, timestamp);

                log.info("成功处理ESP8266电流数据: current={}A, timestamp={}", current, timestamp);
            } catch (Exception e) {
                log.error("处理ESP8266电流数据时发生错误: ", e);
            }

        } else {
            // 处理其他主题的消息（如charge/cmd）
            log.info("收到MQTT消息，主题: {}，内容: {}", topic, payload);
        }
    }
}